package com.service.socket.protocol;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Resolver {
	
	private static final String REGX_PACKET = "(?<length>\\w{4})(?<cmdType>\\w{2})(?<cmdWord>\\w{2})(?<status>\\w{2})(?<deviceNo>\\w{14})(?<dataArea>\\w*)(?<crcValue>\\w{4})";
	
	private static final String regexF057 = "(?<fileName>\\w*)(?<size>\\w{4})(?<index>\\w{8})(?<checksum>\\w{2})";
	
	/**
	 * 解析数据包
	 * @param bytes
	 * @return
	 */
	public static Packet parsePacket(byte[] bytes){
		Packet bean = null;
		try {
			String hex = Conversion.bytesToHexString(Conversion.dataDecode(bytes));
			Pattern p = Pattern.compile(REGX_PACKET);
			Matcher m = p.matcher(hex);
			if (m.find()) {
				bean = new Packet();
				Field[] field = bean.getClass().getFields();
				for(Field f : field){
					try {
						f.setAccessible(true);
						f.set(bean, m.group(f.getName()));
					}catch (Exception e) {
						
					}
				}
			}
		} catch (Exception e) {
			bean = null;
		}
		return bean;
	}
	
	/**
	 * 解析数据区
	 * @param dataArea
	 * @return
	 */
	public static List<String> parseF057(String dataArea){
		List<String> list = null;
		try{
			list = new ArrayList<String>();
			Pattern p = Pattern.compile(regexF057);
			Matcher m = p.matcher(dataArea);
			if(m.find()) {
				int i = 1;
				while(i <= m.groupCount()){
					list.add(m.group(i));
					i++;
				}
			}
		}catch(Exception e){
			list = null;
		}
		return list;
	}
	
}
